package com.hrg.demo.config;

import lombok.Data;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.stereotype.Component;

/**
 * @author shenzq
 */
@Component
public class CronValidator {

    /**
     * 验证cron表达式是否有效
     */
    public static boolean isValid(String cronExpression) {
        try {
            CronExpression.parse(cronExpression);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    /**
     * 验证cron表达式并返回详细信息
     */
    public static ValidationResult validateWithDetails(String cronExpression) {
        ValidationResult result = new ValidationResult();
        result.setCronExpression(cronExpression);

        try {
            CronExpression parsed = CronExpression.parse(cronExpression);
            result.setValid(true);
            result.setNextExecutionTime(parsed.next(java.time.Instant.now()));
            result.setMessage("Cron表达式有效");
        } catch (IllegalArgumentException e) {
            result.setValid(false);
            result.setMessage("Cron表达式无效: " + e.getMessage());
        }

        return result;
    }

    /**
     * 获取cron表达式的下一个执行时间
     */
    public static java.time.Instant getNextExecutionTime(String cronExpression) {
        try {
            CronExpression parsed = CronExpression.parse(cronExpression);
            return parsed.next(java.time.Instant.now());
        } catch (IllegalArgumentException e) {
            return null;
        }
    }

    @Data
    public static class ValidationResult {
        private String cronExpression;
        private boolean valid;
        private String message;
        private java.time.Instant nextExecutionTime;

        public String getNextExecutionTimeFormatted() {
            if (nextExecutionTime == null) {
                return "N/A";
            }
            return java.time.LocalDateTime.ofInstant(nextExecutionTime, java.time.ZoneId.systemDefault())
                    .format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
    }
}
